package net.wenku8.reader.view.online

import androidx.compose.runtime.mutableStateListOf
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import net.wenku8.reader.api.ReviewApi
import net.wenku8.reader.entity.ApiResult
import net.wenku8.reader.model.review.ReviewDataValue
import net.wenku8.reader.state.StateReadOnline
import net.wenku8.reader.view.common.BaseViewModel

class OnlineReviewListViewModel : BaseViewModel() {

    val dataList = mutableStateListOf<ReviewDataValue>()
    private var page = 0
    private var lastPage = false

    fun initData() {
        if (dataList.isNotEmpty()){
            return
        }
        loadNextPage()
    }

    fun loadNextPage(){
        if (lastPage){
            return
        }
        page++
        viewModelScope.launch(Dispatchers.IO) {
            val apiResult = ReviewApi.getReviewList(StateReadOnline.bookId.value, page)
            if (ApiResult.isSuccess(apiResult)){
                if (apiResult.data == null || apiResult.data!!.isEmpty()){
                    lastPage = true
                    return@launch
                }
                dataList.addAll(apiResult.data!!)
            }
        }
    }

}